import dayjs from "../../libs/dayjs";
import { AstContext } from "../context";
import { getRoomInfo } from "../redpacket/getRoomInfo";
import { httpPostV2 } from "../utils/httpPostV2";
import { pullDownToRefresh } from "../utils/pullDownToRefresh";
import { useRoot } from "../utils/useRoot";
import { useSetting } from "../utils/useSetting";
import { AstVisitor } from "../visitor";
let start = true
events.on('start', (isStart: boolean) => {
    start = isStart
})
interface HourTopItem {
    index: number;
    title: string;
    score: number;
}
interface HourList {
    title: string;
    currentDate: string;
    items: Map<string, HourTopItem>;
}
class HourItemVisitor extends AstVisitor {
    visitViewGroup(node: AutoJs.UiObject, ctx: AstContext) {
        const childCount = node.childCount()
        if (childCount === 4) {
            ctx.set('index', parseInt(node.child(0)?.text() || "0"))
            ctx.set('title', node.child(2)?.text())
            const score = node.child(3)?.text() || "0"
            if (score.includes("万")) {
                ctx.set('score', parseFloat(score.replace("万", "")) * 10000)
            } else {
                ctx.set('score', parseInt(score))
            }
        }
    }
    visitTextView(node: AutoJs.UiObject, ctx: AstContext) {
        const text = node.text()
        if (text && text.length > 0) {
            const res = text.match(/本小时榜单前(\d+)$/);
            if (res && res.length > 1) {
                const [, total] = res
                const count = parseInt(total)
                if (count > 0) {
                    ctx.set('total', count)
                }
            }

            const roomTitle = ctx.parent?.get<string>('roomTitle')
            if (roomTitle) {
                if (text === roomTitle) {
                    ctx.parent?.set('status', 'finish')
                    const canClick = ctx.findInParent(node, it => it.clickable())
                    if (canClick) {
                        canClick.click()
                        console.log(`去直播间：` + roomTitle)
                    }
                }
            }
        }
    }
}
const hourItemVisitor = new HourItemVisitor()

class NoCycleListVisitor extends AstVisitor {
    scrollNode: AutoJs.UiObject | undefined = undefined
    visitScrollView(node: AutoJs.UiObject, ctx: AstContext) {
        if (!node.visibleToUser()) return
        const childCount = node.childCount();
        this.scrollNode = node;
        if (childCount === 1) {
            const group = node.child(0)
            if (group) {
                const childCount = group.childCount()
                for (let i = 0; i < childCount; i++) {
                    const child = group.child(i)
                    if (child && node.visibleToUser()) {
                        this.getData(child, ctx)
                    }
                }
            }
        }
    }

    down() {
        this.scrollNode?.scrollDown()
    }

    up() {
        this.scrollNode?.scrollUp()
    }

    /**
     * 返回true 表示到底部了
     * 返回false 表示到顶部了
     */
    private getData(node: AutoJs.UiObject, ctx: AstContext) {
        const items = ctx.get<Map<string, HourTopItem>>('items') || new Map()
        const itemCtx = new AstContext(dayjs, ctx)
        const totalCount = ctx.get<number>('total') || 0
        hourItemVisitor.visit(node, itemCtx)
        if (ctx.get('status') === 'finish') {
            return;
        }
        // 如果有total 则更新
        const total = itemCtx.get<number>('total') || 0
        if (total > 0) {
            ctx.set('total', total)
        }
        const item = itemCtx.all() as HourTopItem
        if (!item.title) {
            return false
        }
        items.set(item.title, item)
        ctx.set('items', items)
        if (item.index === 1) {
            ctx.set('status', 'top')
        }
        if (item.index === totalCount) {
            ctx.set('status', 'end')
        }
        return true
    }
}
const noCycleListVisitor = new NoCycleListVisitor()
class HourListVisitor extends AstVisitor {
    visitTextView(node: AutoJs.UiObject, ctx: AstContext) {
        const text = node.text()
        if (text) {
            const res = text.match(/(.*?)([第|前].*?名主播)?将在/)
            if (res && res.length > 1) {
                const [, area, count] = res;
                ctx.set('area', area)
            }
        }
    }
    visitScrollView(node: AutoJs.UiObject, ctx: AstContext) {
        if (!node.visibleToUser()) return
        const childCount = node.childCount();
        if (childCount === 1) {
            const group = node.child(0)
            if (group) {
                // 统计小时榜变化数据
                const root = useRoot()
                noCycleListVisitor.visit(root, ctx)
                root.recycle()
                // 判断是否到低了
                let status = ctx.get<string>('status') || 'end'
                let start = ctx.get<boolean>('start') || true
                while (!['top', 'finish'].includes(status) && start) {
                    const root = useRoot()
                    noCycleListVisitor.visit(root, ctx)
                    start = ctx.get<boolean>('start') || true
                    status = ctx.get<string>('status')
                    console.log(`当前状态：${status}`)
                    noCycleListVisitor.up()
                    sleep(1000)
                }
                if (noCycleListVisitor.scrollNode) {
                    const bounds = noCycleListVisitor.scrollNode.bounds()
                    if (bounds) {
                        pullDownToRefresh(bounds)
                        sleep(3000)
                    }
                }
                log(`get top success`)
                while (!['end', 'finish'].includes(status) && start) {
                    const root = useRoot()
                    noCycleListVisitor.visit(root, ctx)
                    status = ctx.get<string>('status') || 'end'
                    start = ctx.get<boolean>('start') || true
                    noCycleListVisitor.down()
                    root.recycle()
                    sleep(300)
                }
                log(`get bottom success`)
                let endStatus = ctx.get<string>('status') || 'top'
                while (!['top', 'finish'].includes(endStatus) && start) {
                    const root = useRoot()
                    noCycleListVisitor.visit(root, ctx)
                    endStatus = ctx.get<string>('status') || 'top'
                    start = ctx.get<boolean>('start') || true
                    noCycleListVisitor.up()
                    sleep(300)
                }
                log(`get top success`)
                group.recycle()
            }
        }
    }

}
const hourListVisitor = new HourListVisitor()

export function watchHourTop(start: boolean) {
    console.log(`监控小时榜数据`)
    const ctx = new AstContext(dayjs)
    ctx.set('mode', 'find')
    ctx.set('currentDate', dayjs().format('YYYY-MM-DD HH:mm:ss'))
    ctx.set('start', start)
    console.log(`遍历开始`)
    hourListVisitor.visit(useRoot(), ctx)
    console.log(`遍历结束`)
    const body = ctx.all()
    const items: any[] = [];
    try {
        (body.items as Map<string, HourTopItem>)?.forEach(it => items.push(it));
        const postData = {
            area: body.area || '',
            items: items
        }
        console.log("排行榜名称：" + postData.area)
        httpPostV2('updateHourTop', postData)
    } catch (e) {
        console.error(e)
    }
    console.log(`上传小时榜成功`)
    ctx.set('mode', 'join')
    // 获取小时榜
    const list: any[] = httpPostV2('getHourTop', {
        area: body.area || ""
    }, [])
    let equal288 = list.find(it => it.disScore && it.disScore >= 288 && (it.disScore % 288 === 0))
    if (!equal288) {
        const sortList = list.filter(it => it.disScore && it.disScore >= 288 && it.disScore < 1000).sort((a, b) => a.disScore % 288 - b.disScore % 288)
        if (sortList.length > 0) {
            equal288 = sortList[0]
        }
        console.log(sortList.map(it => it.disScore))
    }
    if (equal288) {
        console.log(`直播间：${equal288.title}} ${equal288.disScore}`)
        ctx.set('roomTitle', equal288.title)
        // 去这个直播间 看看有没有红包
        hourListVisitor.visit(useRoot(), ctx)
        // 查找直播间红包
        const roomInfo = getRoomInfo(start)
        // 保存到服务器
        return;
    } else {
        const setting = useSetting()
        sleep(setting.refreshInterval * 1000)
    }
}
